import { RouterProvider, createRouter } from "@tanstack/react-router";
import ReactDOM from "react-dom/client";
import Loader from "./components/loader";
import { routeTree } from "./routeTree.gen";

{{#if (eq api "orpc")}}
  import { QueryClientProvider } from "@tanstack/react-query";
  import { orpc, queryClient } from "./utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
  import { QueryClientProvider } from "@tanstack/react-query";
  import { queryClient, trpc } from "./utils/trpc";
{{/if}}
{{#if (eq backend "convex")}}
  import { ConvexReactClient } from "convex/react";
  {{#if (eq auth "clerk")}}
  import { ClerkProvider, useAuth } from "@clerk/clerk-react";
  import { ConvexProviderWithClerk } from "convex/react-clerk";
  {{else if (eq auth "better-auth")}}
  import { ConvexBetterAuthProvider } from "@convex-dev/better-auth/react";
  import { authClient } from "@/lib/auth-client";
  {{else}}
  import { ConvexProvider } from "convex/react";
  {{/if}}
  const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string);
{{/if}}

const router = createRouter({
  routeTree,
  defaultPreload: "intent",
  defaultPendingComponent: () => <Loader />,
  {{#if (eq api "orpc")}}
  context: { orpc, queryClient },
  Wrap: function WrapComponent({ children }: { children: React.ReactNode }) {
    return (
      <QueryClientProvider client={queryClient}>
        {children}
      </QueryClientProvider>
    );
  },
  {{else if (eq api "trpc")}}
  context: { trpc, queryClient },
  Wrap: function WrapComponent({ children }: { children: React.ReactNode }) {
    return (
      <QueryClientProvider client={queryClient}>
        {children}
      </QueryClientProvider>
    );
  },
  {{else if (eq backend "convex")}}
  context: {},
  Wrap: function WrapComponent({ children }: { children: React.ReactNode }) {
    {{#if (eq auth "clerk")}}
    return (
      <ClerkProvider
        publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}
      >
        <ConvexProviderWithClerk client={convex} useAuth={useAuth}>
          {children}
        </ConvexProviderWithClerk>
      </ClerkProvider>
    );
    {{else if (eq auth "better-auth")}}
    return <ConvexBetterAuthProvider client={convex} authClient={authClient}>{children}</ConvexBetterAuthProvider>;
    {{else}}
    return <ConvexProvider client={convex}>{children}</ConvexProvider>;
    {{/if}}
  },
  {{else}}
  context: {},
  {{/if}}
});

declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}

const rootElement = document.getElementById("app");

if (!rootElement) {
  throw new Error("Root element not found");
}

if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<RouterProvider router={router} />);
}
